package com.eportal.util;

import com.eportal.exception.MdKnownRunTimeException;

import net.sf.json.JSONObject;

public class WxAccessTokenHelper {

	private static final String GetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
	
	
	private String appId;
	
	private String appSecret;
	
	private String accessToken;
	
	private String getUrl;
	
	public WxAccessTokenHelper() {
	}
	
	
	public WxAccessTokenHelper(String appId, String appSecret) {
		this.appId = appId;
		this.appSecret = appSecret;
		this.getUrl = GetAccessTokenUrl.replace("$appid", appId).replace("$secret", appSecret);
	}



	public String refreshAndGetToken(){
		
		JSONObject json = JSONObject.fromObject(HttpHelper.doGet(getUrl));
		if(json.has("errcode")){
			//throw new 
			throw new MdKnownRunTimeException("call the weixin api error,"+json.toString());
		}else if(json.has("access_token")){
			this.accessToken = json.getString("access_token");
		}else{
			throw new MdKnownRunTimeException("call the weixin api error,"+json.toString());
		}
		 Config.accessTokenMap.put(appId+"_"+appSecret,this.accessToken);
		return this.accessToken;
	}
	
	
	public String getAccessToken() {
		return accessToken;
	}


	public String getAppId() {
		return appId;
	}


	public void setAppId(String appId) {
		this.appId = appId;
	}


	public String getAppSecret() {
		return appSecret;
	}


	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}


	public String getGetUrl() {
		return getUrl;
	}


	public void setGetUrl(String getUrl) {
		this.getUrl = getUrl;
	}


	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	
	
}
